<template>
  <div class="withdraw">
    <el-card>
      <template #header>
        <h3>取款</h3>
      </template>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="源账户ID" prop="fromAccountId">
          <el-input-number v-model="form.fromAccountId" :min="1" />
        </el-form-item>

        <el-form-item label="取款金额" prop="amount">
          <el-input-number
              v-model="form.amount"
              :min="0.01"
              :precision="2"
              :step="100"
              :max="1000000"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { transactionApi } from '../../api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const formRef = ref(null)

const form = ref({
  fromAccountId: null,
  amount: null
})

const rules = {
  fromAccountId: [
    { required: true, message: '请输入源账户ID', trigger: 'blur' },
    { type: 'number', min: 1, message: '账户ID必须大于0', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入取款金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    const response = await transactionApi.withdraw(form.value)
    if (response.state === 2000){
      ElMessage.success('取款成功')
      router.push('/transactions')
    }else {
      ElMessage.error("余额不足");
    }
  } catch (error) {
    ElMessage.error('取款失败')
  }
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style scoped>
.withdraw {
  max-width: 600px;
  margin: 0 auto;
}
</style>